package com.wang.nowcoder.util;

import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wang
 * @ClassName SensitiveFilter
 * @Description 过滤敏感词，使用前缀树装敏感词，通过算法找出语句中的敏感词
 * @date 2021/12/22 14:46
 * @Version 1.0
 */
@Component
public class SensitiveFilter {

    private static final Logger logger = LoggerFactory.getLogger(SensitiveFilter.class);

    /**
     * 替换符
     */
    private static final String REPLACEMENT = "**";

    /**
     * 根节点
     */
    private TrieNode rootNode = new TrieNode();


    /**
     * 初始化时加载前缀树
     * @ PostConstruct表示这个方法是一个初始化方法
     */
    @PostConstruct
    public void init(){
        try ( //获取类加载器
              InputStream is = this.getClass().getClassLoader().getResourceAsStream("sensitive_words.txt");
              BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
              ){
            //定义一个变量用来装取出来的敏感词
           String keyWord;
           while ((keyWord = bufferedReader.readLine())!=null){
               //将敏感词添加到前缀树
               this.addKeyWord(keyWord);
           }
        }catch (IOException e){
            logger.error("加载敏感词文件失败",e.getMessage());
        }

    }
    /**
     * 将一个敏感词添加到前缀树中去
     * @param keyWord 传入的敏感词
     */
    public void addKeyWord(String keyWord){
        TrieNode tempNode = rootNode;
        for (int i=0;i<keyWord.length();i++){
            char c = keyWord.charAt(i);
            TrieNode subNodes = tempNode.getSubNodes(c);

            if (subNodes == null){
                //初始化子节点
                subNodes = new TrieNode();
                tempNode.addSubNode(c,subNodes);
            }

            //指向子节点，进入下一轮循环
            tempNode = subNodes;

            //设置结束标识
            if (i==keyWord.length()-1){
                tempNode.setKeyWordEnd(true);
            }
        }
    }

    /**
     * 过滤敏感词
     * @param text 待过滤的文本
     * @return 过滤后的文本
     */
    public String filter(String text){
        if (StringUtils.isBlank(text)){
            return null;
        }

        //指针1
        TrieNode trieNode = rootNode;
        //指针2
        int begin=0;
        //指针3
        int position=0;
        //结果
        StringBuilder stringBuilder = new StringBuilder();

        while (begin<text.length()){
            if (position<text.length()){
                char c = text.charAt(position);
                //跳过符号
                if(isSymbol(c)){
                    //若指针一处于根节点，将此符号计入结果，让指针二向下走一步
                    if(trieNode == rootNode){
                        stringBuilder.append(c);
                        begin++;
                    }
                    //无论符号在开头还是中间，指针三都向下走一步
                    position++;
                    continue;
                }
                //检查下级节点
                trieNode = trieNode.getSubNodes(c);
                if (trieNode == null){
                    //以begin开头的字符串不是敏感词
                    stringBuilder.append(text.charAt(begin));
                    //进入下一个位置
                    position = ++begin;
                    //重新指向根节点
                    trieNode = rootNode;
                }else if (trieNode.isKeyWordEnd()){
                    //发现敏感词，将begin-position字符串替换掉
                    stringBuilder.append(REPLACEMENT);
                    //进入下一个位置
                    begin=++position;
                    //重新指向根节点
                    trieNode = rootNode;
                }else {
                    //检查下一个字符
                    position++;
                }
            }else {
                //position遍历已经越界任然没有找到敏感词
                stringBuilder.append(text.charAt(begin));
                position = ++begin;
                trieNode = rootNode;
            }
        }
        return stringBuilder.toString();
    }

    /**
     * 判断是否为符号
     * @param c
     * @return
     */
    public boolean isSymbol(Character c){
        //c<0x2E80 || c>0x9FFF为东亚文字范围
        return !CharUtils.isAsciiAlphanumeric(c) && (c<0x2E80 || c>0x9FFF);
    }
    /**
     * 前缀树
     */
    public class TrieNode{
        //关键词结束标语
        private boolean isKeyWordEnd = false;

        //子节点(key是下级字符，value是下级节点)
        private Map<Character, TrieNode> subNodes = new HashMap<>();
        public boolean isKeyWordEnd() {
            return isKeyWordEnd;
        }

        public void setKeyWordEnd(boolean keyWordEnd) {
            isKeyWordEnd = keyWordEnd;
        }

        //添加子节点
        public void addSubNode(Character character, TrieNode node){
            subNodes.put(character,node);
        }

        //获取子节点
        public TrieNode getSubNodes(Character character){
            return subNodes.get(character);
        }
    }
}
